package cn.pomelo.secondskill.controller;

import cn.pomelo.secondskill.common.AjaxResult;
import cn.pomelo.secondskill.model.Address;
import cn.pomelo.secondskill.service.AddressService;
import org.springframework.data.redis.connection.stream.MapRecord;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/address")
public class AddressController {

    @Resource
    private AddressService addressService;

    @RequestMapping("/all")
    public AjaxResult list(Integer userid) {
        List<Address> list = addressService.findByUserid(userid);
        return list == null ? AjaxResult.failure("查询失败") : AjaxResult.success(list);
    }

    @PostMapping("/add")
    public AjaxResult add(@RequestBody Address address) {
        if (address.getDefaultAdd()) { // 如果当前地址是默认地址，去掉其他的默认地址
            addressService.updateDefaultAdd();
        }
        int insert = addressService.insert(address);
        return insert > 0? AjaxResult.success() : AjaxResult.failure("添加失败");
    }

    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody Address record) {
        if (record.getDefaultAdd()) {
            addressService.updateDefaultAdd();
        }
        int update = addressService.updateByPrimaryKey(record);
        return update > 0 ? AjaxResult.success() : AjaxResult.failure("修改失败");
    }

    @RequestMapping("/remove")
    public AjaxResult remove(Integer id) {
        int delete = addressService.deleteByPrimaryKey(id);
        return delete > 0 ? AjaxResult.success() : AjaxResult.failure("删除失败");
    }

}
